<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Spring Boot + Websocket 广播式</title>
</head>
<body onload="disconnect()">
<noscript><h2>貌似你的浏览器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name"/>
        <button id="sendName" onclick="sendName();">发送</button>
        <p id="response"></p>
    </div>
</div>

<script th:src="@{js/sockjs.min.js}"></script>
<script th:src="@{js/stomp.min.js}"></script>
<script th:src="@{js/jquery.min.js}"></script>
<script type="text/javascript">

    var stompClient = null;
    function setConnected(connected) {
        $("#connect").attr("disabled", connected);
        $("#disconnect").attr("disabled", !connected);
        $("#response").html();
    }

    function connect() {
        // 首先创建一个SockJS
        var socket = new SockJS('/endpointkk');
        // WebSocket是基于socket的
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            // 订阅消息目标
            stompClient.subscribe('/topic/getResponse', function (response) {
                $("#response").html(JSON.parse(response.body).responseMessage);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected.");
    }

    function sendName() {
        var name = $('#name').val();
        // 发送消息
        stompClient.send("/welcome", {}, JSON.stringify({"name": name}));
    }

</script>
</body>
</html>
